package com.example.demo.controller.conllection;

import com.example.demo.model.ResponseData;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import io.swagger.annotations.ApiOperation;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author hanqiang
 * @Classname QueryCollectionController
 * @Date 2020/10/4 23:09
 * @Description:
 */
@RestController
@RequestMapping("/collection")
public class QueryCollectionController {

    @Autowired
    MongoTemplate mongoTemplate;

    @ApiOperation(value="查询所有集合",notes="查询所有集合")
    @GetMapping("queryCollectionList")
    public ResponseData queryCollectionList(){
        return ResponseData.success(mongoTemplate.getCollectionNames());
    }

    @ApiOperation(value="查询是否存在该集合",notes="查询是否存在该集合")
    @GetMapping("queryConllection")
    public ResponseData queryConllection(){
        String collectionName="shops";
        return ResponseData.success(mongoTemplate.collectionExists(collectionName));
    }

    @ApiOperation(value="查询集合中数据",notes="查询集合中数据")
    @GetMapping("queryCollectionDocument")
    public ResponseData queryCollectionDocument(){
        String collectionName="shops";
        MongoCollection<Document> collection=mongoTemplate.getCollection(collectionName);
        FindIterable<Document> findIterable=collection.find();
        MongoCursor<Document> mongoCursor=findIterable.iterator();
        while(mongoCursor.hasNext()){
            System.out.println(mongoCursor.next());
        }
        return ResponseData.success();
    }




}
